import { useEffect, useState } from 'react';
import { StatisticCard } from '@ant-design/pro-card';

import { EllipsisOutlined } from '@ant-design/icons';
import moment from 'moment';
import styles from './index.less';
import HomeCharts from '@/components/HomeCharts';
import { message, Tabs } from 'antd';
import {
  chartsService,
  queryConsumption,
  queryGoodsOverdue,
  queryRecharge,
  queryStockWorking,
} from './service';
import CreateForm from './component/CreateForm';
import TableCommon from './component/TableCommon';

const { Statistic } = StatisticCard;
const { TabPane } = Tabs;

const Home = (props) => {
  const [tabsState, setTabsState] = useState(1);
  const [tabsVal, setTabsVal] = useState('今日');
  const [consumption, setConsumption] = useState({});
  const [loading, setLoading] = useState(true);
  const [recharge, setRecharge] = useState({});
  const [openCard, setOpenCard] = useState({});
  const [withdrawal, setWithdrawal] = useState({});
  const [goodsArray, setGoodsArray] = useState([]);
  const [stock, setStock] = useState([]);
  const [modalState, setModalState] = useState(false);
  const [modalVal, setModalVal] = useState('');
  const [chartsData, setChartsData] = useState([]);

  const proCard = (title, titleType, allNum, num, type, styleName) => {
    return (
      <StatisticCard
        className={styleName}
        loading={loading}
        title={title}
        extra={<EllipsisOutlined />}
        statistic={{
          value: allNum,
          suffix: type,
        }}
        onClick={() => {
          return !titleType ? (setModalState(true), setModalVal(title)) : null;
        }}
        footer={
          <>
            {titleType ? (
              <Statistic value={num} title={titleType} suffix="" layout="horizontal" />
            ) : (
              <Statistic title={' '} value={' '} suffix="" layout="horizontal" />
            )}
          </>
        }
        style={{ width: 340 }}
      />
    );
  };
  const handleAll = ({ time, type }) => {
    queryRecharge({
      dayType: time,
      dataType: type,
    })
      .then((res) => {
        const { code } = res;
        if (code === 0) {
          const { data } = res;
          switch (type) {
            case 1:
              setConsumption(data);
              break;
            case 2:
              setRecharge(data);
              break;
            case 3:
              setWithdrawal(data);
              break;
            case 4:
              setOpenCard(data);
              break;
            default:
              break;
          }
        }
      })
      .catch((err) => {
        console.log(err);
      });
  };
  const handleConsumption = (type) => {
    queryConsumption({
      dayType: type,
    })
      .then((res) => {
        const { code } = res;
        setLoading(false);

        return code === 0 ? setConsumption(res.data) : message.info(res.message);
      })
      .catch((err) => {
        console.log(err);
      });
  };
  const handleGoodsOverdue = () => {
    queryGoodsOverdue()
      .then((res) => {
        const { code } = res;
        setLoading(false);
        return code === 0 ? setGoodsArray(res.data) : message.info(res.message);
      })
      .catch((err) => {
        console.log(err);
      });
    queryStockWorking()
      .then((res) => {
        const { code } = res;
        setLoading(false);

        return code === 0 ? setStock(res.data) : message.info(res.message);
      })
      .catch((err) => {
        console.log(err);
      });
  };
  const handleCharts = (payload, timeArray) => {
    const arr = [];
    for (let i in timeArray) {
      let list;
      if (payload.indexOf('金额') !== -1) {
        list = {
          time: i,
          value: timeArray[i],
          type: payload,
        };
      } else {
        list = {
          time: i,
          count: timeArray[i],
          name: payload,
        };
      }
      arr.push(list);
    }
    arr.sort((a, b) => a.time - b.time);
    if (arr[0].time.length === 2) {
      arr.map((item) => {
        // console.log((Number(item.value) / 10000).toFixed(5));
        // item.value
        //   ? (item.value = Number(Number(item.value) / 10000).toFixed(5))
        //   : (item.count = Number(Number(item.count) / 10000).toFixed(5));
        return (item.time = item.time + ':00');
      });
    } else {
      // arr.map((item) => {
      //   return item.value
      //     ? (item.value = Number(Number(item.value) / 10000).toFixed(5))
      //     : (item.count = Number(Number(item.count) / 10000).toFixed(5));
      // });
    }
    return arr;
  };
  const handleChartsLine = (payload, timeArray) => {};
  const chartsChange = (time, date, payload) => {
    chartsService(time, date, {
      startTime: payload?.startTime,
      endTime: payload?.endTime,
    })
      .then(async (res) => {
        const { code } = res;
        if (code === 0) {
          const {
            data: { consumeBar, consumeLine, openCardBar, openCardLine, rechargeBar, rechargeLine },
          } = res;
          const consumArr = await handleCharts('消费金额', consumeBar);
          const openCardArr = await handleCharts('开卡金额', openCardBar);

          const consumeLineArr = await handleCharts('消费笔数', consumeLine);
          const openCardLineArr = await handleCharts('开卡笔数', openCardLine);
          //const rechargeBarArr = await handleCharts('充值金额', rechargeBar);
          //const rechargeLineArr = await handleCharts('充值笔数', rechargeLine);
          //const chartsList = consumArr.concat(openCardArr).concat(rechargeBarArr);
          const chartsList = consumArr.concat(openCardArr);
         // const LineList = consumeLineArr.concat(openCardLineArr).concat(rechargeLineArr);
          const LineList = consumeLineArr.concat(openCardLineArr);
          setChartsData([chartsList, LineList]);
        } else {
          message.info(res.message);
        }
      })
      .catch((err) => {
        console.log(err);
      });
  };
  const changeTime = (e) => {
    setTabsState(e);
    const nowDate = moment(new Date()).day(1).format('YYYY-MM-DD');
    const dateArray = nowDate.split('-');
    const startTime = moment(new Date()).day(0).format('YYYY-MM-DD');
    const endTime = moment(new Date()).day(6).format('YYYY-MM-DD');
    const monthTime = moment(new Date(dateArray[0], Number(dateArray[1]) - 1, 1)).format(
      'YYYY-MM-DD',
    ); // 当月第一天
    const yearTime = `${new Date().getFullYear()}-01-01`;
    switch (e) {
      case '1':
        setTabsVal('今年');
        handleAll({
          time: 'year',
          type: 1,
        });
        handleAll({
          time: 'year',
          type: 2,
        });
        handleAll({
          time: 'year',
          type: 3,
        });
        handleAll({
          time: 'year',
          type: 4,
        });
        //handleConsumption('year');
        chartsChange('year', yearTime);
        break;
      case '2':
        setTabsVal('今月');
        handleAll({
          time: 'month',
          type: 1,
        });
        handleAll({
          time: 'month',
          type: 2,
        });
        handleAll({
          time: 'month',
          type: 3,
        });
        handleAll({
          time: 'month',
          type: 4,
        });
        //handleConsumption('month');
        chartsChange('month', monthTime);
        break;
      case '3':
        setTabsVal('今周');
        handleAll({
          time: 'week',
          type: 1,
        });

        handleAll({
          time: 'week',
          type: 2,
        });
        handleAll({
          time: 'week',
          type: 3,
        });
        handleAll({
          time: 'week',
          type: 4,
        });
        //handleConsumption('week');
        chartsChange('week', '', { startTime, endTime });
        break;

      case '4':
        setTabsVal('今日');
        handleAll({
          time: 'day',
          type: 1,
        });
        handleAll({
          time: 'day',
          type: 2,
        });
        handleAll({
          time: 'day',
          type: 3,
        });
        handleAll({
          time: 'day',
          type: 4,
        });
        //handleConsumption('day');
        chartsChange('day', moment(new Date()).format('YYYY-MM-DD'));
        break;
      default:
        break;
    }
  };

  useEffect(() => {
    const nowDate = moment(new Date()).format('YYYY-MM-DD');
    handleAll({
      time: 'day',
      type: 1,
    });
    handleAll({
      time: 'day',
      type: 2,
    });
    handleAll({
      time: 'day',
      type: 3,
    });
    handleAll({
      time: 'day',
      type: 4,
    });
    //handleConsumption('day');
    handleGoodsOverdue();
    chartsChange('day', nowDate);
  }, []);
  return (
    <div className={styles.homeDiv}>

      <Tabs
        defaultActiveKey="4"
        onChange={changeTime}
        style={{ background: 'white', paddingLeft: 10 }}
      >
        <TabPane tab="日统计" key="4"></TabPane>
        <TabPane tab="周统计" key="3"></TabPane>
        <TabPane tab="月统计" key="2"></TabPane>
        <TabPane tab="年统计" key="1"></TabPane>
      </Tabs>
      <div className={styles.homeHeadCard}>
        {proCard(
          tabsVal + '总销售金额',
          '总销售笔数',
          consumption?.amount,
          consumption?.count,
          '元',
          styles.default_card,
        )}
        {proCard(
          tabsVal + '总会员消费金额',
          '总会员消费笔数',
          recharge?.amount,
          recharge?.count,
          '元',
          styles.default_card,
        )}
        {/*{proCard(*/}
        {/*  tabsVal + '总退款金额',*/}
        {/*  '总退款笔数',*/}
        {/*  withdrawal?.amount,*/}
        {/*  withdrawal?.count,*/}
        {/*  '元',*/}
        {/*  styles.default_card,*/}
        {/*)}*/}
        {proCard(
          tabsVal + '总开卡金额',
          '总开卡笔数',
          openCard?.amount,
          openCard?.count,
          '元',
          styles.default_card,
        )}
        {/* {proCard('库存报警', '', stock.length, '', '条', styles.default_orign)} */}
        {/* {proCard('商品临期报警', '', goodsArray.length, '', '条', styles.default_orign)} */}
      </div>
      <div className={styles.homeHeadCard} style={{ height: 800 }}>
        <div className={styles.chartsDiv}>
          <HomeCharts salesData={chartsData} />
        </div>
        {/* <div className={styles.rightCard}>
          {proCard(
            tabsVal + '总提现金额',
            '总提现笔数',
            withdrawal?.amount,
            withdrawal?.count,
            '元',
            styles.default_card,
          )}
          {proCard(
            tabsVal + '总开卡金额',
            '总开卡笔数',
            openCard?.amount,
            openCard?.count,
            '元',
            styles.default_card,
          )}
          <div></div>
          <div></div>
        </div> */}
      </div>
      <CreateForm
        width={1300}
        title={modalVal}
        onCancel={() => setModalState(false)}
        modalVisible={modalState}
      >
        <TableCommon payOrderValues={modalVal === '库存报警' ? stock : goodsArray} />
      </CreateForm>
    </div>
  );
};
export default Home;
